package model.tokens;

import java.util.Deque;
import java.util.Stack;
import java.util.Queue;

import model.parser.FunctionTable;
import model.semantics.Node;

/**
 * Operators are things like +, *, /, -.
 */

public class OperatorToken<T> extends FunctionalToken<T> {
    public OperatorToken(TokenConstructorArguments<T> args) {
        super(args);
    }

    /**
     * Handle the processing of operators in the Shunting-Yard algorithm.
     * 
     * @param state
     *            .operatorStack the stack of operator tokens.
     * @param state
     *            .output the queue of tokens state.output by the algorithm.
     */
    @Override
    public void process(Automaton<T> state) {
        /*
         * While there is an operator on the stack with higher precedence than
         * this token, shunt it to the state.output queue, then add the token to
         * the stack.
         */
        while (!state.operatorStack.empty()
                && state.operatorStack.peek() instanceof OperatorToken
                && ((OperatorToken<?>) state.operatorStack.peek())
                        .getPrecedence() > getPrecedence()) {
            state.output.add(((OperatorToken<T>) state.operatorStack.pop())
                    .makeNewInstance(state.output));
        }
        state.operatorStack.push(this);
    }

    @Override
    public Node<T> makeNewInstance(Deque<Node<T>> queue) {
        return myFunctionDefinition.makeNewInstance(queue, false);
    }

}
